<template>
  <div class="app-container customer-div">
    <el-menu :default-active="trackingParams.type" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="self">我负责的</el-menu-item>
      <el-menu-item index="sub" v-if="isCanCustomerByDept">部门</el-menu-item>
      <el-menu-item index="all" v-if="isCanCustomerByAll">全部</el-menu-item>
    </el-menu>

    <div style="margin-top: 20px">
<!--      <el-button-->
<!--              size="small"-->
<!--              v-if="trackingParams.type == 'self'"-->
<!--              @click="showTracking('add',null)"-->
<!--              type="primary">-->
<!--        新增跟进记录-->
<!--      </el-button>-->
    </div>

    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="trackingParams" size="mini" label-width="100px">
        <el-form-item label="客户名称：">
          <el-select
            clearable
            @change="changeCustomerId($event,2)"
            v-model="trackingParams.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod2"
            :loading="loading">
            <el-option
              v-for="item in customerList2"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人：">
          <el-select v-model="trackingParams.contactId" placeholder="请选择" clearable filterable>
             <el-option v-for="item in contactList2"  :key="item.contactId" :label="item.contactName" :value="item.contactId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人：">
          <el-select v-model="trackingParams.chargeUserId" placeholder="请选择" clearable filterable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.realName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容：">
            <el-input v-model="trackingParams.trackingContent"></el-input>
        </el-form-item>
        <el-form-item label="跟进方式：">
          <el-select v-model="trackingParams.trackingTypeId" placeholder="请选择" clearable>
            <el-option v-for="item in customerTrackingList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进人：">
          <el-select v-model="trackingParams.trackingUserId" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期：">
          <el-date-picker
            :default-time="['00:00:00', '23:59:59']"
            v-model="trackingParams.createTime"
            value-format="timestamp"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="潜在等级：">
          <el-select v-model.number="trackingParams.customerPotential" class="input-width" style="width:195px" placeholder="请选择" clearable >
            <el-option
                    v-for="item in customerPotentialList"
                    :key="item.customerPotentialId"
                    :label="item.customerPotentialValue"
                    :value="item.customerPotentialId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="跟进类型：">
          <el-select v-model="trackingParams.isInvalid" placeholder="请选择" clearable>
            <el-option  value="0" label="有效" key="0"></el-option>
            <el-option  value="1" label="无效" key="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
                  v-if="trackingExport"
                  @click="downloadExcel">
            导出
          </el-button>

          <el-button
                  v-if="trackingParams.type == 'all'"
                  @click="showImport2()">
            导入
          </el-button>

        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="trackingLoading"
        :data="trackingList"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
                label="公司名称"
                width="300">
            <template slot-scope="scope">
              <el-link @click="toDetail(scope.row)" type="primary">
                {{scope.row.customerName}}
              </el-link>
            </template>
        </el-table-column>
        <el-table-column
          prop="contactName"
          label="联系人姓名"
          align="center"
          width="150">
        </el-table-column>
        <el-table-column
                prop="customerPotential"
                label="潜在等级"
                align="center"
                width="150">
        </el-table-column>
        <el-table-column
          prop="trackingType"
          label="跟进方式"
          align="center"
          width="100">
        </el-table-column>

        <el-table-column
          prop="developStep"
          label="开发阶段"
          align="center"
          width="100">
        </el-table-column>

        <el-table-column
          prop="trackingContent"
          label="跟进业务"
          width="180">
        </el-table-column>


        <el-table-column
          prop="fromBuyReason"
          label="客户原因"
          width="180">
        </el-table-column>

        <el-table-column
                prop="goodsLineNames"
                label="产品线"
                width="180">
        </el-table-column>

        <el-table-column
          label="跟进日期"
          width="180"
          align="center">
          <template slot-scope="scope">
            {{scope.row.trackingTime*1000 | formatTime}}
          </template>
        </el-table-column>
        <el-table-column
          prop="trackingRemark"
          label="备注"
          width="400">
        </el-table-column>
        <el-table-column
          align="center"
          prop="isInvalid"
          label="跟进类型"
          width="100">
          <template slot-scope="scope">
            {{scope.row.isInvalid == 0 ? '有效' : scope.row.isInvalid == 1 ? '无效' : ''}}
          </template>
        </el-table-column>
        <el-table-column
          label="跟进人"
          width="180"
          align="center">
          <template slot-scope="scope">
            {{scope.row.trackingUser}}
          </template>
        </el-table-column>
        <el-table-column
          label="创建日期"
          width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.createTime}}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              v-if="trackingParams.type == 'self'"
              type="text"
              size="mini"
              @click="showTracking('edit',scope.row)">编辑
            </el-button>
            <el-button
                    v-if="trackingParams.type != 'self'"
                    type="text"
                    size="mini"
                    @click="showTracking('see',scope.row)">查看
            </el-button>
            <el-button
              v-if="trackingParams.type == 'self'"
              type="text"
              size="mini"
              @click="delTracking(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChangeTracking"
        @current-change="handleCurrentChangeTracking"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="trackingParams.pageNum"
        :page-size="trackingParams.pageSize"
        :page-sizes="[10,15,20]"
        :total="trackingCount">
      </el-pagination>
    </div>

    <!--新增/编辑跟进-->
    <el-dialog
            :close-on-click-modal="false"
      :title="title2"
      :beforeClose="handleClose2"
      :visible.sync="dialogVisible2"
      width="600px">
      <el-form :model="trackingForm" size="mini" label-width="120px" :rules="rules" ref="trackingForm">
        <el-form-item label=" 客户名称：" prop="customerId">
          <el-select
            :disabled="showTrackingType!='add'"
            @change="changeCustomerId($event,1)"
            v-model="trackingForm.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in customerList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人：" prop="contactId">
          <el-select  v-model="trackingForm.contactId"  placeholder="请选择" :disabled="showTrackingType=='see'" @change="changeContactId">
            <el-option v-for="item in contactList"  :key="item.contactId" :label="item.contactName" :value="item.contactId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否有采购决定权：">
          <span style="font-size:12px" v-if="isBuyPermission != -1">{{isBuyPermission==1 ? '是' : '否'}}</span>
        </el-form-item>
        <el-form-item label="产品线：" prop="goodsLineIds">
          <el-select  v-model="trackingForm.goodsLineIds" multiple placeholder="请选择" :disabled="showTrackingType=='see'" multiple>
            <el-option v-for="item in goodsLineListOps"  :key="item.goodsLineId" :label="item.goodsLineValue + '/' + item.cglCurrentDevelopStateStr" :value="item.goodsLineId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进日期：" prop="trackingTime">
          <el-date-picker
            :disabled="showTrackingType=='see'"
            v-model="trackingForm.trackingTime"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="timestamp"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="跟进方式：" prop="trackingTypeId">
          <el-select  v-model="trackingForm.trackingTypeId" placeholder="请选择" :disabled="showTrackingType=='see'">
            <el-option v-for="item in customerTrackingList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开发阶段：" prop="developStep">
          <el-select  v-model="trackingForm.developStep" placeholder="请选择" :disabled="showTrackingType=='see'">
            <el-option v-for="item in developStepList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户原因：" prop="fromBuyReason" v-if="developStepVal == '促成交'">
          <el-select  v-model="trackingForm.fromBuyReason" placeholder="请选择" :disabled="showTrackingType=='see'">
            <el-option v-for="item in fromBuyReasonList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进类型：" prop="isInvalid">
          <el-radio-group v-model="trackingForm.isInvalid" :disabled="showTrackingType=='see'">
            <el-radio :label="0">有效</el-radio>
            <el-radio :label="1">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跟进内容：" prop="trackingContent">
          <el-input v-model="trackingForm.trackingContent" type="textarea" :rows="2" :disabled="showTrackingType=='see'" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
        <el-form-item label="图片上传：" v-if="showTrackingType!='see' || (showTrackingType=='see'&&trackingForm.trackingPics.length > 0)">
          <div style="width:80px;height:80px;object-fit: contain;margin-bottom:10px;margin-right:10px;vertical-align: middle;position: relative;display:inline-block" v-for="(item,index) in trackingForm.trackingPics">
            <img :src="item"  style="width:100%;height:100%;object-fit: contain;"/>
            <i class="el-icon-error" style="cursor: pointer;position: absolute;right:0;top:0;" @click="delImg(index)"></i>
          </div>
          <el-upload
            drag
            v-if="trackingForm.trackingPics.length<9 && showTrackingType!='see'"
            :data="uploadToken"
            action="https://upload.qiniup.com"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
<!--            <i class="el-icon-plus avatar-uploader-icon"></i>-->
          </el-upload>
        </el-form-item>
        <el-form-item label="下次跟进日期：">
          <el-date-picker
            :disabled="showTrackingType=='see'"
            v-model="trackingForm.nextTrackingTime"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="timestamp"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注：">
          <el-input v-model="trackingForm.trackingRemark"  type="textarea" :rows="2" :disabled="showTrackingType=='see'" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="showTrackingType!='see'">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
          <el-button @click="handleClose2">关 闭</el-button>
      </span>
    </el-dialog>

    <!--跟进记录导入-->
    <el-dialog
            :show-close="showClose2"
            :close-on-click-modal="showClose2"
            :close-on-press-escape="showClose2"
            title="跟进记录导入"
            :beforeClose="beforeCloseEditPrice2"
            :visible.sync="dialogVisibleImprot2"
            width="500px">
      <div>
        <el-alert
                title="请先按约定好的字段导入跟进列表"
                type="warning"
                :closable="false">
        </el-alert>
        <div class="upload-div" style="margin-top:20px">
          <input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
          <el-button type="primary" size="small" :loading="uploadLoading">选择上传文件</el-button>
        </div>
        <div style="margin:20px auto;margin-bottom:0;word-break:break-all;text-align: left;line-height:20px;background: #fef0f0;color:#f56c6c;padding:10px" v-if="msg2!=''">
          <div style="max-height: 90px;overflow: auto;padding:10px"><div v-if="showFial2">添加失败：</div>{{msg2}}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleEditPriceConfirm2" :loading="EditLoading2">提 交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
    import { getTrackingList, customerPotential,saveTrackingInfo, editTrackingInfo, delTrackingInfo, getContactList, getCustomerSetting,getCustomerOption,getUserOption,getQiniuToken,goodsLineList} from '@/api/partner'
    import {trackingImport} from '@/api/company';
    import {lastTracking} from '@/api/product'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultTrackingForm = {
        customerId:'',
        customerName:'',
        contactId:'',
        trackingTypeId:'',
        trackingContent:'',
        trackingTime:'',
        trackingPics:[],
        trackingRemark:'',
        nextTrackingTime:'',
        goodsLineIds:[],
        isInvalid:0,
        developStep:'',
        fromBuyReason:'',
    };
    export default {
        name: "index",
        data(){
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                activeIndex:'1',
                trackingParams:{
                    type:'self',
                    customerId:'',
                    trackingTypeId:'',
                    contactId:'',
                    trackingUserId:'',
                    createTime:[],
                    trackingContent:'',
                    customerPotential:"",
                    chargeUserId:'',
                    isInvalid:'',
                    pageNum:1,
                    pageSize:10,
                },
                trackingList:[],
                trackingCount:0,
                trackingLoading:false,
                dialogVisible:false,
                imgSrc:'',
                dialogVisible2:false,
                title2:'',
                btnLoading2:false,
                trackingForm:JSON.parse(JSON.stringify(defaultTrackingForm)),
                rules:{
                    customerId:[{required: true, message: '请选择客户', trigger: 'change'},],
                    contactId:[{required: true, message: '请选择联系人', trigger: 'change'},],
                    trackingTypeId:[{required: true, message: '请选择跟进方式', trigger: 'change'},],
                    trackingContent:[{required: true, message: '请填写跟进内容', trigger: 'blur'},],
                    trackingTime:[{required: true, message: '请选择跟进日期', trigger: 'change'},],
                    goodsLineIds:[{required: true, message: '请选择产品线', trigger: 'change'},],
                    isInvalid:[{required: true, message: '此项必填', trigger: 'change'},],
                    developStep:[{required: true, message: '此项必填', trigger: 'change'},],
                  fromBuyReason:[{required: true, message: '此项必填', trigger: 'change'},],
                },
                contactList:[],//联系人列表
                contactList2:[],//联系人列表
                customerStateList: [],
                customerTypeList: [],
                customerTrackingList: [],
                customerSourceList: [],
                customerQualityList: [],
                customerDegreeList: [],
                customerIndustryList:[],
                loading:false,
                customerList:[],
                customerList2:[],
                userOptionList:[],
                uploadToken:{
                    token:'',
                },
                imgDomain:'',
                showTrackingType:'',
                isBuyPermission:-1,
              customerPotentialList:[],
              goodsLineListOps:[],

              showClose2:true,
              dialogVisibleImprot2:false,//批量导入弹窗
              EditLoading2:false,//批量导入提交按钮loadin
              showFial2:false,//批量导入失败
              msg2:'',//上传文件信息
              uploadLoading:false,
              da:[],
              file:null,
              developStepList:[],
              fromBuyReasonList:[],
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),
          isCanTrackingByAdd() {
            if (this.roles.indexOf("trackingByAdd") != -1) {
              return true
            } else {
              return false
            }
          },
          isCanTrackingByEdit() {
            if (this.roles.indexOf("trackingByEdit") != -1) {
              return true
            } else {
              return false
            }
          },
          isCanTrackingDelete() {
            if (this.roles.indexOf("trackingDelete") != -1) {
              return true
            } else {
              return false
            }
          },
          isCanCustomerByDept() {
            if (this.roles.indexOf("customerByDept") != -1) {
              return true
            } else {
              return false
            }
          },
          isCanCustomerByAll() {
            if (this.roles.indexOf("customerByAll") != -1) {
              return true
            } else {
              return false
            }
          },
          trackingExport() {
            if (this.roles.indexOf("trackingExport") != -1) {
              return true
            } else {
              return false
            }
          },

          developStepVal(){
            if(this.trackingForm.developStep != '' && this.developStepList.length > 0){
              console.log(this.trackingForm.developStep);
              console.log(this.developStepList)
              let curitem = this.developStepList.find((el)=>{
                return el.cddId == this.trackingForm.developStep;
              })
              console.log("curitem",curitem)
              return curitem ? curitem.cddValue  : ''
            }else{
              return ''
            }
          },
        },
        created() {
            if(this.$route.query.type){
              let start = new Date(new Date().toLocaleDateString()).getTime();
              let end = parseInt(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1000);
              switch (this.$route.query.type) {
                case 'my':
                  this.trackingParams.type = 'self';
                  break;
                case 'myDay':
                  this.trackingParams.type = 'self';
                  this.trackingParams.createTime = [start,end];
                  break;
                case 'dept':
                  this.trackingParams.type = 'sub';
                  break;
                case 'deptDay':
                  this.trackingParams.type = 'sub';
                  this.trackingParams.createTime = [start,end];
                  break;
                case 'company':
                  this.trackingParams.type = 'all';
                  break;
                case 'companyDay':
                  this.trackingParams.type = 'all';
                  this.trackingParams.createTime = [start,end];
                  break;
              }
            }
            this.getTrackingListData();
            this.getCustomerSettingList();
            this.getUserOptionList();
            this.getUploadToken();
            this.getCustomerPotential();
            // this.getGoodsLineListOps();
        },
        filters: {
            formatTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd')
            },
        },
        methods:{
          //导入excel
          importfxx(obj) {
            let _this = this;
            this.uploadLoading = true;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
            var reader = new FileReader();
            //if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function(f) {
              var binary = "";
              var rABS = false; //是否将文件读取为二进制字符串
              var pt = this;
              var wb; //读取完成的数据
              var outdata;
              var reader = new FileReader();
              reader.onload = function(e) {
                var bytes = new Uint8Array(reader.result);
                var length = bytes.byteLength;
                for(var i = 0; i < length; i++) {
                  binary += String.fromCharCode(bytes[i]);
                }
                var XLSX = require('xlsx');
                if(rABS) {
                  wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                    type: 'base64'
                  });
                } else {
                  wb = XLSX.read(binary, {
                    type: 'binary'
                  });
                }
                outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
                // if (outdata.length  > 200){
                //   _this.$message({
                //     message: '最大上传200条',
                //     type: 'error'
                //   });
                //   var test = document.getElementById('upload');
                //   test.value = '';
                //   return false;
                // }
                _this.da = [...outdata];
                console.log("da",_this.da)
                let arr = [];

                let para = {
                  withList: arr
                };
                _this.$message({
                  message: '上传成功，请点击提交',
                  type: 'success'
                });
                _this.uploadLoading = false;
              };
              reader.readAsArrayBuffer(f);
            };
            if(rABS) {
              reader.readAsArrayBuffer(f);
            } else {
              reader.readAsBinaryString(f);
            }
          },

          //显示导入跟进记录弹窗
          showImport2(){

            this.showFial2 = false;
            this.EditLoading2 = false;
            this.uploadLoading = false;
            this.msg2 = '';
            this.dialogVisibleImprot2 = true;
          },
          //关闭导入跟进记录弹窗
          beforeCloseEditPrice2(){
            $("#upload").val('');
            this.da = [];
            this.msg2 = '';
            this.dialogVisibleImprot2 = false;
          },


          //提交导入跟进记录
          handleEditPriceConfirm2(){
            if (this.da.length == 0){
              this.$message({
                message: '上传数据为空',
                type: 'warning'
              });
              return false;
            }
            this.msg2 = '后台处理中，请耐心等待……';
            this.showFial2 = false;
            this.EditLoading2 = true;
            this.showClose2 = false;
            trackingImport({list:this.da}).then((res)=>{
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.msg2 = '修改成功';
              this.EditLoading2 = false;
              this.dialogVisible2 = false;
              this.showClose2 = true;
              this.da = [];
              this.dialogVisibleImprot2 = false;
              $("#upload").val('');
              this.getUserList();
            }).catch((err)=>{
              this.msg2 = err.msg;
              this.showFial2 = true;
              this.EditLoading2 = false;
              $("#upload").val('');
              this.showClose2 = true;
            })
          },

          //产品线选项
          getGoodsLineListOps(){
            goodsLineList({customerId:this.trackingForm.customerId}).then((res)=>{
              this.goodsLineListOps = res;
            })
          },
          //下载excle
          downloadExcel(){
            let data = JSON.parse(JSON.stringify(this.trackingParams));
            if(data.createTime && data.createTime != ''){
              data.createTime[0] = data.createTime[0]/1000;
              data.createTime[1] = data.createTime[1]/1000;
            }
            data.isExport = 1;
            getTrackingList(data).then((res)=>{
              require.ensure([], () => {
                const { export_json_to_excel } = require('sheet/Export2Excel');
                const tHeader = res.title;
                const filterVal = res.columns;
                const list = res.list;
                const data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, res.fileName);
              })
            })
          },

          //下载表格数据格式化
          formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
          },
          //获取潜在等级
          getCustomerPotential(){
            customerPotential().then((res)=>{
              this.customerPotentialList = res;
            })
          },
            //切换联系人
            changeContactId(){
              let item = this.contactList.find((el)=>{
                return this.trackingForm.contactId == el.contactId
              });
              this.isBuyPermission = item.isBuyPermission;
            },
            //去详情页
            toDetail(item){
              this.$router.push({name:'customerDetail',query:{id:item.customerId}})
            },
            /**
             * 切换选择状态
             */
            handleSelect(key, keyPath){
                this.trackingParams.type = key;
                this.handleSearchList();
            },
            //获取员工下拉选项
            getUserOptionList(){
                getUserOption().then((res)=>{
                    this.userOptionList = res;
                })
            },
            //切换公司
            changeCustomerId(e,type){
                if(type == 1 ){
                    this.trackingForm.contactId = null;
                    this.getContactListData(1,false);
                    this.getGoodsLineListOps();
                    this.trackingForm.goodsLineIds = [];
                    // this.getdevelopStep();
                }else{
                    this.trackingParams.contactId = null;
                    this.getContactListData(2,false);
                }
            },

            //获取客户开发等级
            getdevelopStep(){
              lastTracking({customerId:this.trackingForm.customerId}).then((res)=>{
                this.trackingForm.developStep = res.developStep != 0 ? res.developStep : ''
              })
            },

            //获取联系人列表
            getContactListData(type,isEdit){
                if(type == 1 ){
                      getContactList({customerId:this.trackingForm.customerId}).then((res)=>{
                          this.contactList = res;
                          let i = res.findIndex((el)=>{
                              return el.isMainContact == 1
                          });
                          if(!isEdit){
                              this.trackingForm.contactId = this.contactList[i] ? this.contactList[i].contactId : null;
                          }
                        })
                }else{
                    getContactList({customerId:this.trackingParams.customerId}).then((res)=> {
                        this.contactList2 = res;
                    })
                }
            },

            //获取客户列表
            remoteMethod(query) {
                if(query && query!= '') {
                  this.loading = true;
                  let data = {};
                  data.keywords = query;
                  if(this.trackingParams.type == 'self'){
                    data.chargeId = this.userId
                  }
                  getCustomerOption(data).then(response => {
                      this.customerList = response;
                      this.loading = false;
                  }).catch(()=>{
                      this.loading = false;
                  });
                }
            },

            //查询获取客户列表
            remoteMethod2(query) {
                if(query && query!= ''){
                    this.loading = true;
                    getCustomerOption({keywords:query}).then(response => {
                        this.customerList2 = response;
                        this.loading = false;
                    }).catch(()=>{
                        this.loading = false;
                    });
                }
            },

            //获取客户配置
            getCustomerSettingList() {
                getCustomerSetting().then((res) => {
                    res.forEach((el) => {
                        if (el.cdtCode == 'customer_state') {
                            this.customerStateList = el.data
                        } else if (el.cdtCode == 'customer_type') {
                            this.customerTypeList = el.data;
                        } else if (el.cdtCode == 'customer_tracking') {
                            this.customerTrackingList = el.data;
                        } else if (el.cdtCode == 'customer_source') {
                            this.customerSourceList = el.data;
                        } else if (el.cdtCode == 'customer_quality') {
                            this.customerQualityList = el.data;
                        } else if (el.cdtCode == 'customer_degree') {
                            this.customerDegreeList = el.data;
                        } else if (el.cdtCode == 'customer_industry') {
                            this.customerIndustryList = el.data;
                        }else if (el.cdtCode == 'develop_step') {
                          this.developStepList = el.data;
                        }else if (el.cdtCode == 'from_buy_reason') {
                          this.fromBuyReasonList = el.data;
                        }
                    });
                })
            },
            handleSearchList(){
                this.trackingParams.pageNum = 1;
                this.getTrackingListData();
            },
            //获取客户跟进记录
            getTrackingListData(){
                this.trackingLoading = true;
                let data = JSON.parse(JSON.stringify(this.trackingParams));
                if(data.createTime && data.createTime != ''){
                    data.createTime[0] = data.createTime[0]/1000;
                    data.createTime[1] = data.createTime[1]/1000;
                }
                getTrackingList(data).then((res)=>{
                    this.trackingList = res.list;
                    this.trackingCount = res.count;
                    this.trackingLoading = false;
                }).catch(()=>{
                    this.trackingLoading = false;
                })
            },

            handleSizeChangeTracking(val){
                this.trackingParams.pageNum = 1;
                this.trackingParams.pageSize = val;
                this.getTrackingListData();
            },
            handleCurrentChangeTracking(val){
                this.trackingParams.pageNum = val;
                this.getTrackingListData();
            },
            //获取七牛TOKEN
            getUploadToken(){
                getQiniuToken().then((res)=>{
                    this.uploadToken.token = res.token;
                    this.imgDomain = res.domain
                })
            },

            //上传图片
            handleAvatarSuccess(res){
                console.log("res",res);
                this.trackingForm.trackingPics.push(this.imgDomain+res.key)

            },

            //删除图片
            delImg(index){
                this.trackingForm.trackingPics.splice(index,1)
            },

            //删除跟进
            delTracking(item){
                this.$confirm('确定删除跟进记录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delTrackingInfo({trackingId:item.trackingId}).then(()=>{
                        this.getTrackingListData();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //显示新增/编辑跟进
            showTracking(type,item){
                this.title2 = type == 'add' ? '新增跟进' : type == 'edit' ?'编辑跟进' : '查看跟进';
                this.showTrackingType = type
                this.dialogVisible2 = true;
                if(type=='add'){
                    this.trackingForm = JSON.parse(JSON.stringify(defaultTrackingForm));
                    let date = new Date();
                    this.trackingForm.trackingTime = date.getTime();
                    this.trackingForm.trackingTypeId = this.customerTrackingList[0] ? this.customerTrackingList[0].cddId :'';
                }else{
                    this.trackingForm = JSON.parse(JSON.stringify(item));
                    this.remoteMethod(item.customerName);
                    this.getContactListData(1,true);
                    this.getGoodsLineListOps();
                    this.trackingForm.trackingPics = item.trackingPics != '' ? item.trackingPics : [];
                    this.trackingForm.trackingTime = item.trackingTime != '' ? item.trackingTime * 1000 : '';
                    this.trackingForm.nextTrackingTime = item.nextTrackingTime != '' ? item.nextTrackingTime * 1000: '';
                    this.trackingForm.developStep = item.developStepId;
                    this.trackingForm.fromBuyReason = item.fromBuyReasonId;
                }
            },

            //关闭跟进弹窗
            handleClose2(){
                // this.$refs.trackingForm.clearValidate();
                this.dialogVisible2 = false;
                this.btnLoading2 = false;
                this.contactList = [];
                this.customerList = [];
            },

            //提交跟进
            handleConfirm2(){
                this.$refs.trackingForm.validate((valid) => {
                    if (valid) {
                        this.btnLoading2 = true;
                        let data = JSON.parse(JSON.stringify(this.trackingForm));
                        data.trackingTime = data.trackingTime/1000;
                        data.nextTrackingTime = data.nextTrackingTime != '' ?  data.nextTrackingTime/1000 :  data.nextTrackingTime;
                        // data.trackingPics = data.trackingPics.length > 0 ? data.trackingPics.join(",") : '';
                        let fn = data.trackingId ? editTrackingInfo : saveTrackingInfo;
                        fn(data).then((res)=>{
                            this.btnLoading2 = false;
                            this.handleClose2();
                            this.getTrackingListData();
                        })
                    }
                })
            },
        },
    }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: block;
  }
  .upload-div{
    text-align: center;
    position:relative;
    #upload{

      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
</style>
